package logic

import (
	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"
	"baidu/modil/mysql"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookLikeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookLikeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookLikeLogic {
	return &BookLikeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookLikeLogic) BookLike(in *baidurpc.BookLikeRequest) (*baidurpc.BookLikeResponse, error) {
	// todo: add your logic here and delete this line
	var likes mysql.Likes
	mysql.DB.Debug().Where("user_id = ?", in.UserId).Where("book_id=?", in.BookId).Find(&likes)
	if likes.ID != 0 {
		return nil, fmt.Errorf("该用户已给,此帖子点赞了")
	}
	m := mysql.Likes{
		UserId: int(in.UserId),
		BookId: int(in.BookId),
	}
	mysql.DB.Debug().Create(&m)
	var likesNum mysql.Book
	mysql.DB.Debug().Where("id = ?", in.BookId).Find(&likesNum)
	likesNum.Likes = likesNum.Likes + 1
	mysql.DB.Debug().Updates(likesNum)
	return &baidurpc.BookLikeResponse{
		LikesId: int64(m.ID),
	}, nil
}
